package ar.edu.unq.tpi.constriu.c1.tejeda.Dominio.Agenda;


import java.lang.reflect.Field;
import java.util.List;

import org.apache.log4j.Logger;
import org.uqbar.commons.model.Filter;

import com.db4o.query.Predicate;
import com.uqbar.commons.ReflectionUtils;

/**
 * Esta clase se utiliza como criterio de filtro para la busqueda.
 * @author nnydejesus
 */
public class FilterPredicate<T> extends Predicate<T>{
	private static final long serialVersionUID = 1L;

    private static org.apache.log4j.Logger LOGGER = Logger.getLogger(FilterPredicate.class);
	private T example;
	private List<Field> fields;

	public FilterPredicate(T example) {
		this.example = example;
		fields = org.uqbar.commons.utils.ReflectionUtils.getAllFieldAnnotation(example, Filter.class);
	}

	@Override
	public boolean match(T object) {
		if(example.getClass().equals(object.getClass()))
			return isPassFilter(object);
		else 
			return false;
	}

	/**
	 * 
	 * @param object
	 * @return
	 */
	protected boolean isPassFilter(T object) {
		StringBuilder log = new StringBuilder();
		log.append("Filtrando el objecto "+object+"\n");
		boolean pass = true;
		for (Field field : fields) {
			Object exampleFieldValue = ReflectionUtils.getFieldValue(example, field);
			Object objectFieldValue = ReflectionUtils.getFieldValue(object, field);
			log.append("	"+" campo "+field.getName() + " valor del objeto example: "+exampleFieldValue + " valor del objeto de la base "+ objectFieldValue+"\n");
			if(!FilterHome.getInstance().getFilter(objectFieldValue.getClass()).pass(objectFieldValue, exampleFieldValue)){
				pass= false;
			}
		}
		LOGGER.info(log);
		return pass;
	}
}